package com.cskaoyan.dao;

import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserInfo;
import com.cskaoyan.util.DruidUtils;
import com.cskaoyan.util.TransactionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public List<User> selectUsers(UserInfo userInfo) {
        StringBuffer sqlSB = new StringBuffer();
        sqlSB.append("select id,username,mobile,age from user_t ");
        ArrayList params = new ArrayList();
        if (userInfo.getUsername() != null || userInfo.getMobile() != null) {
            sqlSB.append("where ");
        }
        if (userInfo.getUsername() != null) {
            sqlSB.append("username = ？");
            params.add(userInfo.getUsername());
        }
        if (userInfo.getMobile() != null) {
            if (userInfo.getUsername() != null) {
                sqlSB.append(" and ");
            }
            sqlSB.append("mobile = ? ");
            params.add(userInfo.getMobile());
        }
        sqlSB.append("order by ").append(userInfo.getSort()).append(" ").append(userInfo.getOrder()).append(" limit ").append(userInfo.getLimit());

        QueryRunner queryRunner = new QueryRunner();
        try {
            List<User> users = queryRunner.query(DruidUtils.getConnection(),sqlSB.toString(), new BeanListHandler<>(User.class), params.toArray());
            return users;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insert(User user) {
        String sql = "insert into user_t (username,mobile,age) values (?, ?, ?)";

        QueryRunner queryRunner = new QueryRunner();
        try {
            queryRunner.update(TransactionUtils.getConnection(), sql, user.getUsername(), user.getMobile(),user.getAge());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }



}
